import re
from PIL import ImageFile
ImageFile.LOAD_TRUNCATED_IMAGES = True
class ClassifyHandlerBase:
    _instances = {}
    def __new__(cls, *args, **kwargs):
        if cls not in cls._instances:
            instance = super(ClassifyHandlerBase, cls).__new__(cls)
            cls._instances[cls] = instance
        return cls._instances[cls]
    @staticmethod
    def verify(cls,validate_text:str):
        raise NotImplementedError
        
class BankCardClassifyHandler(ClassifyHandlerBase):
    """银行卡判断"""
    def __init__(self, app):
        if not hasattr(self, 'initialized'):  # 避免多次执行__init__
            self.parent_classify_name = "卡证"
            self.classify_name = '银行卡'
            self.initialized = True
            self.base_regex = r"(?=.*银行)(?=.*银联)|(?=.*借记卡)(?=.*银联)|(?=.*贷记卡)(?=.*银联)"
            self.base_regex_pattern = re.compile(self.base_regex, re.MULTILINE)
            
            self.bank_card_regex = r'\b\d{16,19}\b'
            self.bank_card_pattern = re.compile(self.bank_card_regex, re.MULTILINE)
        else:
            app.ctx.logger.info(f"{self.__class__.__name__}已加载...")

    def verify(self, validate_text: str):
        verify_res = {
            "classifyName":self.parent_classify_name,
            "subClassifyName":self.classify_name,
            "thirdClassifyName": self.classify_name,
            "confidence": 0
        }
        try:
            validate_text = validate_text.replace("\n", "")
            verify_res['confidence'] = 1 if bool(self.base_regex_pattern.search(validate_text)) else 0
            return verify_res
        except Exception as e:
            self.app.ctx.logger.error(f"{self.classify_name}识别失败：{e}")
            verify_res['confidence'] = 0
            return verify_res
        
class IdCardClassifyHandler(ClassifyHandlerBase):
    """身份证判断"""
    def __init__(self, app):
        if not hasattr(self, 'initialized'):  # 避免多次执行__init__
            self.parent_classify_name = "卡证"
            self.classify_name = '身份证'
            self.initialized = True
            self.base_regex = r"((?=.*姓名)(?=.*公民身份号码))|((?=.*中华人民共和国)(?=.*居民身份证)(?=.*签发机关))"
            self.base_regex_pattern = re.compile(self.base_regex, re.MULTILINE)
        else:
            app.ctx.logger.info(f"{self.__class__.__name__}已加载...")

    def verify(self, validate_text: str):
        verify_res = {
            "classifyName":self.parent_classify_name,
            "subClassifyName":self.classify_name,
            "thirdClassifyName": self.classify_name,
            "confidence": 0
        }
        try:
            validate_text = validate_text.replace("\n", "")
            verify_res['confidence'] = 1 if bool(self.base_regex_pattern.search(validate_text)) else 0
            return verify_res
        except Exception as e:
            self.app.ctx.logger.error(f"{self.classify_name}识别失败：{e}")
            verify_res['confidence'] = 0
            return verify_res

class DriverLicenseClassifyHandler(ClassifyHandlerBase):
    """驾驶证判断"""
    def __init__(self, app):
        if not hasattr(self, 'initialized'):  # 避免多次执行__init__
            self.parent_classify_name = "卡证"
            self.classify_name = '驾驶证'
            self.initialized = True
            self.base_regex = r"(?=.*中华人民共和国机动车驾驶证)(?=.*姓名)(?=.*初次领证日期)(?=.*机动车驾驶证)"
            self.base_regex_pattern = re.compile(self.base_regex, re.MULTILINE)
        else:
            app.ctx.logger.info(f"{self.__class__.__name__}已加载...")

    def verify(self, validate_text: str):
        verify_res = {
            "classifyName":self.parent_classify_name,
            "subClassifyName":self.classify_name,
            "thirdClassifyName": self.classify_name,
            "confidence": 0
        }
        try:
            validate_text = validate_text.replace("\n", "")
            verify_res['confidence'] = 1 if bool(self.base_regex_pattern.search(validate_text)) else 0
            return verify_res
        except Exception as e:
            self.app.ctx.logger.error(f"{self.classify_name}识别失败：{e}")
            verify_res['confidence'] = 0
            return verify_res
    
class HouseholdRegisterClassifyHandler(ClassifyHandlerBase):
    """户口本判断"""
    def __init__(self, app):
        if not hasattr(self, 'initialized'):  # 避免多次执行__init__
            self.parent_classify_name = "卡证"
            self.classify_name = '户口簿'
            self.initialized = True
            self.base_regex = r"((?=.*常住人口登记卡)(?=.*籍)(?=.*宗教信仰))|((?=.*居民户口簿)(?=.*中华人民共和国公安部制))"
            self.base_regex_pattern = re.compile(self.base_regex, re.MULTILINE)
        else:
            app.ctx.logger.info(f"{self.__class__.__name__}已加载...")

    def verify(self, validate_text: str):
        verify_res = {
            "classifyName":self.parent_classify_name,
            "subClassifyName":self.classify_name,
            "thirdClassifyName": self.classify_name,
            "confidence": 0
        }
        try:
            validate_text = validate_text.replace("\n", "")
            verify_res['confidence'] = 1 if bool(self.base_regex_pattern.search(validate_text)) else 0
            return verify_res
        except Exception as e:
            self.app.ctx.logger.error(f"{self.classify_name}识别失败：{e}")
            verify_res['confidence'] = 0
            return verify_res
        
class ChinesePassportClassifyHandler(ClassifyHandlerBase):
    """中国护照判断"""
    def __init__(self, app):
        if not hasattr(self, 'initialized'):  # 避免多次执行__init__
            self.parent_classify_name = "卡证"
            self.classify_name = '中国护照'
            self.initialized = True
            self.base_regex = (r"((?=.*中华人民共和国|.*中华人民|.*china|.*taiwan"
                               #r"|.*Australian|.*Italian|.*Spanish|.*Dutch"
                               #r"|.*Swiss|.*United|.*American|.*France|.*France|.*French|.*Canada|.*Canadian|.*Germany"
                               #r"|.*German|.*INDIA|.*KOREA|.*JAPAN"
                               r"))"
                               r"(?=.*护照|.*passport|.*passeport)")
            self.base_regex_pattern = re.compile(self.base_regex, re.MULTILINE|re.IGNORECASE)
        else:
            app.ctx.logger.info(f"{self.__class__.__name__}已加载...")

    def verify(self, validate_text: str):
        verify_res = {
            "classifyName":self.parent_classify_name,
            "subClassifyName":self.classify_name,
            "thirdClassifyName": self.classify_name,
            "confidence": 0
        }
        try:
            validate_text = validate_text.replace("\n", "")
            verify_res['confidence'] = 1 if bool(self.base_regex_pattern.search(validate_text)) else 0
            return verify_res
        except Exception as e:
            self.app.ctx.logger.error(f"{self.classify_name}识别失败：{e}")
            verify_res['confidence'] = 0
            return verify_res
                
class BusinessLicenseClassifyHandler(ClassifyHandlerBase):
    """营业执照判断"""
    def __init__(self, app):
        if not hasattr(self, 'initialized'):  # 避免多次执行__init__
            self.parent_classify_name = "卡证"
            self.classify_name = '营业执照'
            self.initialized = True
            self.base_regex = r"(?=.*营业执照)(?=.*经营)(?=.*统一社会信用代码)"
            self.base_regex_pattern = re.compile(self.base_regex, re.MULTILINE)
        else:
            app.ctx.logger.info(f"{self.__class__.__name__}已加载...")

    def verify(self, validate_text: str):
        verify_res = {
            "classifyName":self.parent_classify_name,
            "subClassifyName":self.classify_name,
            "thirdClassifyName": self.classify_name,
            "confidence": 0
        }
        try:
            validate_text = validate_text.replace("\n", "")
            verify_res['confidence'] = 1 if bool(self.base_regex_pattern.search(validate_text)) else 0
            return verify_res
        except Exception as e:
            self.app.ctx.logger.error(f"{self.classify_name}识别失败：{e}")
            verify_res['confidence'] = 0
            return verify_res
        
class TransferRecordClassifyHandler(ClassifyHandlerBase):
    """转账记录截图判断"""
    def __init__(self, app):
        if not hasattr(self, 'initialized'):  # 避免多次执行__init__
            self.parent_classify_name = "文档"
            self.classify_name = '转账记录'
            self.initialized = True
            self.base_regex = r"((?=.*转账)|(?=.*支付))(?=.*款)((?=.*成功)|(?=.*收钱)|(?=.*到账))"
            self.base_regex_pattern = re.compile(self.base_regex, re.MULTILINE)
        else:
            app.ctx.logger.info(f"{self.__class__.__name__}已加载...")

    def verify(self, validate_text: str):
        verify_res = {
            "classifyName":self.parent_classify_name,
            "subClassifyName":self.classify_name,
            "thirdClassifyName": self.classify_name,
            "confidence": 0
        }
        try:
            validate_text = validate_text.replace("\n", "")
            verify_res['confidence'] = 1 if bool(self.base_regex_pattern.search(validate_text)) else 0
            return verify_res
        except Exception as e:
            self.app.ctx.logger.error(f"{self.classify_name}识别失败：{e}")
            verify_res['confidence'] = 0
            return verify_res
        
class SmsVerifyCodeClassifyHandler(ClassifyHandlerBase):
    """短信验证码判断"""
    def __init__(self, app):
        if not hasattr(self, 'initialized'):  # 避免多次执行__init__
            self.parent_classify_name = "文档"
            self.classify_name = '短信验证码'
            self.initialized = True
            self.base_regex = r"(?=.*验证码)((?=.*有效)|(?=.*分钟内)|(?=.*iMessage))"
            self.base_regex_pattern = re.compile(self.base_regex, re.MULTILINE)
        else:
            app.ctx.logger.info(f"{self.__class__.__name__}已加载...")

    def verify(self, validate_text: str):
        verify_res = {
            "classifyName":self.parent_classify_name,
            "subClassifyName":self.classify_name,
            "thirdClassifyName": self.classify_name,
            "confidence": 0
        }
        try:
            validate_text = validate_text.replace("\n", "")
            verify_res['confidence'] = 1 if bool(self.base_regex_pattern.search(validate_text)) else 0
            return verify_res
        except Exception as e:
            self.app.ctx.logger.error(f"{self.classify_name}识别失败：{e}")
            verify_res['confidence'] = 0
            return verify_res

class StockClassifyHandler(ClassifyHandlerBase):
    """股票截图判断"""
    def __init__(self, app):
        if not hasattr(self, 'initialized'):  # 避免多次执行__init__
            self.parent_classify_name = "文档"
            self.classify_name = '股票截图'
            self.initialized = True
            self.base_regex = r"(?=.*日K)(?=.*周K)(?=.*月K)(?=.*市值)(?=.*量比)|(?=.*买入)(?=.*卖出)(?=.*持仓)(?=.*盈)"
            self.base_regex_pattern = re.compile(self.base_regex, re.MULTILINE|re.IGNORECASE)
        else:
            app.ctx.logger.info(f"{self.__class__.__name__}已加载...")

    def verify(self, validate_text: str):
        verify_res = {
            "classifyName":self.parent_classify_name,
            "subClassifyName":self.classify_name,
            "thirdClassifyName": self.classify_name,
            "confidence": 0
        }
        try:
            validate_text = validate_text.replace("\n", "")
            verify_res['confidence'] = 1 if bool(self.base_regex_pattern.search(validate_text)) else 0
            return verify_res
        except Exception as e:
            self.app.ctx.logger.error(f"{self.classify_name}识别失败：{e}")
            verify_res['confidence'] = 0
            return verify_res
        
class LotteryClassifyHandler(ClassifyHandlerBase):
    """彩票截图判断"""
    def __init__(self, app):
        if not hasattr(self, 'initialized'):  # 避免多次执行__init__
            self.parent_classify_name = "文档"
            self.classify_name = '彩票截图'
            self.initialized = True
            allow_words={"&&&"}
            self.base_regex = r"(?=.*体彩)(?=.*期)(?=.*开奖)(?=.*大乐透)"
            self.base_regex_pattern = re.compile(self.base_regex, re.MULTILINE)
        else:
            app.ctx.logger.info(f"{self.__class__.__name__}已加载...")

    def verify(self, validate_text: str):
        verify_res = {
            "classifyName":self.parent_classify_name,
            "subClassifyName":self.classify_name,
            "thirdClassifyName": self.classify_name,
            "confidence": 0
        }
        try:
            validate_text = validate_text.replace("\n", "")
            verify_res['confidence'] = 1 if bool(self.base_regex_pattern.search(validate_text)) else 0
            return verify_res
        except Exception as e:
            self.app.ctx.logger.error(f"{self.classify_name}识别失败：{e}")
            verify_res['confidence'] = 0
            return verify_res

class AirTicketClassifyHandler(ClassifyHandlerBase):
    """机票登机牌判断"""
    def __init__(self, app):
        if not hasattr(self, 'initialized'):  # 避免多次执行__init__
            self.parent_classify_name = "文档"
            self.classify_name = '机票登机牌'
            self.initialized = True
            self.base_regex = r"(?=.*姓名)(?=.*航班)((?=.*舱位)|(?=.*航位))"
            self.base_regex_pattern = re.compile(self.base_regex, re.MULTILINE)
        else:
            app.ctx.logger.info(f"{self.__class__.__name__}已加载...")

    def verify(self, validate_text: str):
        verify_res = {
            "classifyName":self.parent_classify_name,
            "subClassifyName":self.classify_name,
            "thirdClassifyName": self.classify_name,
            "confidence": 0
        }
        try:
            validate_text = validate_text.replace("\n", "")
            verify_res['confidence'] = 1 if bool(self.base_regex_pattern.search(validate_text)) else 0
            return verify_res
        except Exception as e:
            self.app.ctx.logger.error(f"{self.classify_name}识别失败：{e}")
            verify_res['confidence'] = 0
            return verify_res

class ExpressDocClassifyHandler(ClassifyHandlerBase):
    """快递单判断"""
    def __init__(self, app):
        if not hasattr(self, 'initialized'):  # 避免多次执行__init__
            self.parent_classify_name = "文档"
            self.classify_name = '快递单'
            self.initialized = True
            self.base_regex = r"((?=.*收)(?=.*寄))((?=.*中通)|(?=.*京东)|(?=.*韵达)|(?=.*顺丰)|(?=.*圆通)|(?=.*邮政)|(?=.*极兔)|(?=.*德邦)|(?=.*百世)|(?=.*菜鸟)|(?=.*安能)|(?=.*包裹)|(?=.*随机)|(?=.*集))"
            self.base_regex_pattern = re.compile(self.base_regex, re.MULTILINE)
        else:
            app.ctx.logger.info(f"{self.__class__.__name__}已加载...")

    def verify(self, validate_text: str):
        verify_res = {
            "classifyName":self.parent_classify_name,
            "subClassifyName":self.classify_name,
            "thirdClassifyName": self.classify_name,
            "confidence": 0
        }
        try:
            validate_text = validate_text.replace("\n", "")
            verify_res['confidence'] = 1 if bool(self.base_regex_pattern.search(validate_text)) else 0
            return verify_res
        except Exception as e:
            self.app.ctx.logger.error(f"{self.classify_name}识别失败：{e}")
            verify_res['confidence'] = 0
            return verify_res
        
if __name__ == '__main__':
    from sanic import Sanic
    app = Sanic("ces")
    id_card_handler = ExpressDocClassifyHandler(app)
    res = id_card_handler.verify("""
拼多多
快递
包裹
2022/09/0517:59:07第1/4个
777104465872537
777104465872537
777104465872537
610-M10
0146
中山中转包
集
梦想成真18575882173
收
广东省佛山市顺德区容桂南
777104465872537
777104465872537
区发晶三横路六号，梁世飞
寄
詹江淮02081747458
广东省广州市白云区金盆村军民三路二号筋斗云仓
M10
777104465872537
脱毛膏腋下腿毛非私处唇部唇毛温和去除小胡子
汗毛，，一盒（半疗程7%用户选择）*1
总：1件
卖家备注：
已验视
买家留言：
拼多多
多实惠多乐趣




                         """)
    print(res)